package rpc.core.plugin.impl.proxy;

import java.lang.reflect.Method;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.core.FlowReq;
import rpc.core.FlowRes;
import rpc.utils.ExceptionUtils;

/*********
 *
 *
 *@author 197
 *@date 2020/8/5 18:16
 *
 **/


public class RpcClientServiceProxy implements ServiceProxy {

  private static final Logger logger = LoggerFactory.getLogger(RpcClientServiceProxy.class);
  private final Class<?> reqClass;
  private final Method method;
  private final Object impl;

  public RpcClientServiceProxy(Method method, Object impl) {
    this.method = method;
    this.reqClass = method.getParameterTypes()[0];
    this.impl = impl;
  }

  public Method getMethod() {
    return method;
  }

  @Override
  public CompletableFuture<FlowRes> invoke(FlowReq req) {

    logger.info("method:{}, impl:{}, req:{}", method.getName(), impl.getClass(), req);
    Object invoke = null;
    try {
      invoke = this.method.invoke(this.impl, req);
    } catch (Exception e) {
      logger.error("exception:{} stackTrace:{}", e.getMessage(), ExceptionUtils.getTrace(e));
    }

    return CompletableFuture.completedFuture((FlowRes) invoke);
  }
}